/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import classNames from 'classnames';
import { isFunction } from 'lodash';

type triggerChangeEvTypes = {
  type: 'click' | 'outter';
};
const KbPagination: React.FC<{
  hasMore: boolean;
  current?: number;
  pageSize?: number;
  actionRef?: any;
  tableRef?: any;
  onChange?: (v: number) => void;
}> = (props) => {
  const { current = 1, pageSize = 20, hasMore = false, actionRef, tableRef, onChange } = props;

  const pageRef = useRef({ page: 1 });
  const [page, setPage] = useState<number>(1);

  const triggerChange = (v: number, ev?: triggerChangeEvTypes) => {
    pageRef.current.page = v;
    setPage(v);
    if (isFunction(onChange)) {
      onChange(v);
    }
    if (ev?.type === 'click' && tableRef?.current) {
      tableRef?.current.reload();
    }
  };

  useEffect(() => {
    if (actionRef?.current) {
      actionRef.current = {
        getValues: () => {
          return {
            current: pageRef.current.page,
            pageSize,
          };
        },
        setValues: (v: number) => {
          triggerChange(v);
        },
      };
    }
  }, [page, pageSize]);

  useEffect(() => {
    if (current) {
      setPage(current * 1 || 1);
    }
  }, [current]);

  const handleClickBar = (key: string) => {
    // console.log('handleClickBar', key);
    let v = page * 1 || 1;
    switch (key) {
      case 'prev':
        v--;
        break;
      case 'next':
        v++;
        break;
    }
    triggerChange(v, { type: 'click' });
  };

  const disPrev = !(page > 1);
  const disNext = !hasMore;
  const prevCls = classNames('ant-pagination-prev', {
    'ant-pagination-disabled': disPrev,
  });
  const nextCls = classNames('ant-pagination-next', {
    'ant-pagination-disabled': disNext,
  });
  return (
    <>
      <ul className='ant-pagination ant-table-pagination ant-table-pagination-right'>
        <li className={prevCls}>
          <Button
            className='ant-pagination-item-link'
            type='link'
            disabled={disPrev}
            onClick={handleClickBar.bind(null, 'prev')}
          >
            <LeftOutlined />
          </Button>
        </li>
        <li className='ant-pagination-item ant-pagination-item-1 ant-pagination-item-active'>
          <a>{page}</a>
        </li>
        <li className={nextCls}>
          <Button
            className='ant-pagination-item-link'
            type='link'
            disabled={disNext}
            onClick={handleClickBar.bind(null, 'next')}
          >
            <RightOutlined />
          </Button>
        </li>
      </ul>
    </>
  );
};

export default KbPagination;
